package cn.fboost.mtos.controller;

import cn.fboost.mtos.annotation.RoleIs;
import cn.fboost.mtos.dto.Response;
import cn.fboost.mtos.dto.internal.Session;
import cn.fboost.mtos.dto.request.SystemConfigUpdateRequest;
import cn.fboost.mtos.service.SystemService;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

/**
 * 系统配置控制器 - 管理员专用
 */
@RoleIs({Session.Role.ADMIN})
@RestController
@RequestMapping("system")
public class SystemController {
    private final SystemService systemService;

    public SystemController(SystemService systemService) {
        this.systemService = systemService;
    }

    /**
     * 获取系统配置项
     *
     * @param key 配置项名称
     * @return {@link Response}
     */
    @GetMapping("config/{key}")
    public Response getSetting(@PathVariable("key") @Valid @NotBlank(message = "配置项名称不能为空") String key) {
        return systemService.getConfig(key);
    }

    /**
     * 获取系统配置项
     *
     * @param prefix 配置项名称前缀
     * @return {@link Response}
     */
    @GetMapping("config/prefix/{prefix}")
    public Response getSettingByPrefix(@PathVariable("prefix") @Valid @NotBlank(message = "配置项名称前缀不能为空") String prefix) {
        return systemService.getConfigByPrefix(prefix);
    }

    /**
     * 更新系统配置项
     *
     * @param request {@link SystemConfigUpdateRequest}
     * @return {@link Response}
     */
    @PostMapping("config/update")
    public Response updateSetting(@RequestBody @Valid SystemConfigUpdateRequest[] request) {
        return systemService.updateConfig(request);
    }

    /**
     * 清除配置缓存
     *
     * @return {@link Response}
     */
    @DeleteMapping("config/cache")
    public Response clearConfigCache() {
        return systemService.clearConfigCache();
    }
}
